//引入
import Vue from 'vue';
import Vuex from 'vuex';
//注册
Vue.use(Vuex);
//存储数据
const state = {
  todoList: [
    { id: 2, todoName: '吃饭', isDone: false },
    { id: 1, todoName: '睡觉', isDone: true },
  ],
};
//异步操作，发送请求
const actions = {
  deleteTask(context, val) {
    setTimeout(() => {
      context.commit('DELECT_TASK', val);
    }, 1000);
  },
};
//操作数据
const mutations = {
  //两个参数， state数据， payload接收传入过来的数据
  //改变数据状态
  CHANGE_TASK(state, payload) {
    state.todoList.find((item) => {
      if (item.id === payload) {
        item.isDone = !item.isDone;
      }
    });
  },
  //添加数据
  ADD(state, payload) {
    state.todoList.unshift({
      id: state.todoList ? state.todoList[0].id + 1 : 1,
      todoName: payload,
      isDone: false,
    });
  },
  //删除
  DELECT_TASK(state, id) {
    state.todoList = state.todoList.filter((item) => item.id !== id);
  },
  //编辑
  UPDATE_EDIT(state, payload) {
    state.todoList.find((item) => {
      if (item.id === payload.id) {
        item.todoName = payload.todoName;
      }
    });
  },
  //删除所有已完成的
  CLEAR_COMPONENT(state, payload) {
    state.todoList = state.todoList.filter((item) => !item.isDone);
  },
  //全选
  SELECT_ALL(state,val){
    state.todoList.forEach(item => {
      item.isDone = val
    });
  }
};
//计算数据
const getters = {
  //返回未完成的总数
  activeTask(state) {
    return state.todoList.filter((item) => !item.isDone).length;
  },
  doneTask(state) {
    return state.todoList.filter((item) => item.isDone).length;
  },
};
//创建store并导出
const store = new Vuex.Store({
  state,
  actions,
  mutations,
  getters,
});
export default store;
